"""Import batch model for CRM-SaaS system."""

from __future__ import annotations

import enum
from typing import TYPE_CHECKING
from uuid import UUID

from sqlalchemy import ForeignKey, String, Integer, Enum as SQLEnum
from sqlalchemy.orm import Mapped, mapped_column, relationship
from sqlalchemy.dialects.postgresql import UUID as PostgresUUID

from ..db.base_class import Base
from ..models.base import TimestampMixin

if TYPE_CHECKING:
    from ..models.user import User
    from ..models.import_record import ImportRecord


class ImportStatus(str, enum.Enum):
    """Import batch status."""

    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"


class ImportBatch(Base, TimestampMixin):
    """Import batch tracking."""

    __tablename__ = "importbatch"
    id: Mapped[UUID] = mapped_column(PostgresUUID(as_uuid=True), primary_key=True, index=True)
    filename: Mapped[str] = mapped_column(String(255), nullable=False)
    channel_hint: Mapped[str | None] = mapped_column(String(50), nullable=True)
    record_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
    status: Mapped[ImportStatus] = mapped_column(
        SQLEnum(ImportStatus), nullable=False, default=ImportStatus.PROCESSING
    )

    # Validation statistics
    errors_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of records with validation errors"
    )
    warnings_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of records with warnings"
    )
    duplicates_count: Mapped[int] = mapped_column(
        Integer, nullable=False, default=0, comment="Number of potential duplicate records found"
    )

    # Foreign keys
    imported_by: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False, index=True)

    # Relationships
    importer: Mapped[User] = relationship("User")
    import_records: Mapped[list[ImportRecord]] = relationship(
        "ImportRecord",
        back_populates="import_batch",
        cascade="all, delete-orphan",
    )
